/**
*@Create:YMHUI
*@DateTime:2019/10/188:53
*@Description:TODO
**/
<template>
  <div>
    <div v-if="!isMultipleDimension">
      <el-table :data="questionnaire.dimensions" size="mini"
                border heigth="400px" style="width: 100%"
                highlight-current-row>
        <el-table-column label="编号" prop="sort">
        </el-table-column>
        <el-table-column label="名称" prop="name">
            <template slot-scope="scope">
                <el-input v-if="scope.row.edit"
                          v-model="scope.row.name"/>
                <span v-else>{{scope.row.name}}</span>
            </template>
        </el-table-column>
          <el-table-column label="权重" prop="weight">
              <template slot-scope="scope">
                  <el-input v-if="scope.row.edit"
                            v-model="scope.row.weight"/>
                  <span v-else>{{scope.row.weight}}</span>
              </template>
          </el-table-column>
        <el-table-column label="题目数量" prop="questionNum">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
              <el-button type="text" size="medium" @click="handleEdit(scope.$index,scope.row)">
                  <i class="el-icon-edit" aria-hidden="true"/>
              </el-button>
              <el-button type="text" size="medium" @click="deleteDimension(scope.$index)">
                  <i class="el-icon-delete" aria-hidden="true"/>
              </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="el-table-add-row" style="width: 99.2%;" @click="addOneLevel">
        <span>+添加一级维度</span>
      </div>
    </div>
    <div v-else>
      <el-row style="margin-bottom: .5em">
          <el-col :span="1" class="headerItem">编号</el-col>
          <el-col :span="6" class="headerItem" style="text-align: right">名称</el-col>
          <el-col :span="6" class="headerItem" style="text-align: right">权重</el-col>
          <el-col :span="5" class="headerItem" style="text-align: right">题目数量</el-col>
          <el-col :span="6" class="headerItem" style="text-align: right">操作</el-col>
      </el-row>
      <el-tree
        :data="questionnaire.dimensions"
        :props="defaultProps"
        accordion
        node-key="number"
        default-expand-all
        :expand-on-click-node="false"
        :render-content="renderContent"
        style="text-align: left">
      </el-tree>
      <div class="el-table-add-row" style="width: 99.2%;" @click="addOneLevel">
        <span>+添加一级维度</span>
      </div>
    </div>
    <div style="text-align: right; margin-top: 1em;">
      <el-checkbox v-model="isMultipleDimension" @change="checkChange">
        多级维度
      </el-checkbox>
    </div>
    <dimension-edit-dialog ref="dimensionEdit">
    </dimension-edit-dialog>
  </div>
</template>

<script>
    import {mapActions, mapGetters} from 'vuex';
    import DimensionEditDialog from "./DimensionEditDialog";
    import Util from "../../common/util";
    import {MessageBox} from 'element-ui'

    export default {
        name: "DimensionManager",
        components:{
            DimensionEditDialog
        },
        computed:{
            ...mapGetters('questionnaire', [
                'currentQuestionnaire'
            ])
        },
        data() {
            return {
                tempName: '',
                popoverEditVisible: false,
                isMultipleDimension: false,
                defaultProps: {
                    children: 'children',
                    label: 'name'
                },
                questionnaire: {},
                editFormVisible: false
            }
        },
        methods: {
            ...mapActions('questionnaire', [
                'setCurrentQuestionnaire',
                'deleteDimensionAct'
            ]),
            handleEdit(index, row) {
                this.$refs.dimensionEdit.open(row);
                this.$emit('modalAppendToBody', false);
            },
            addOneLevel() {
                let sort = this.questionnaire.dimensions.length;
                this.questionnaire.dimensions.push({
                    id: '',
                    sort: sort + 1,
                    name: '新建维度' + this.questionnaire.dimensions.length,
                    questions: [],
                    children: [],
                    questionNum: 0,
                    weight: 0,
                    dimensionTempTag: Util.createRandomId()
                });
                this.setCurrentQuestionnaire(this.questionnaire);
            },
            async deleteDimension(index) {
                if (this.questionnaire.dimensions[index].questionNum > 0) {
                    await MessageBox.alert("维度包含绑定题目，不能删除！", "警告");
                    return;
                }
                if (this.questionnaire.dimensions[index].id !== "") {
                    await this.deleteDimensionAct({id: this.questionnaire.dimensions[index].id});
                }
                this.questionnaire.dimensions.splice(index, 1);
                for (let i in this.questionnaire.dimensions) {
                    this.questionnaire.dimensions[i].sort = parseInt(i) + 1;
                }
                this.setCurrentQuestionnaire(this.questionnaire);
            },
            append(dimension) {
                if (!dimension.children) {
                    this.$set(dimension, 'children', []);
                }
                let sort = dimension.children.length;
                const newDimension = {
                    id: '',
                    sort: sort + 1,
                    name: dimension.name + "-" + dimension.children.length,
                    questions: [],
                    children: [],
                    questionNum: 0,
                    weight: 0,
                    edit: false,
                    dimensionTempTag: Util.createRandomId()
                };
                dimension.children.push(newDimension);
                this.setCurrentQuestionnaire(this.questionnaire);
            },
            async remove(node, dimension) {
                const parent = node.parent;
                const children = parent.data.children || parent.data;
                const index = children.findIndex(d => d.name === dimension.name);
                if (children[index].questions.length > 0) {
                    alert("维度下绑定有题目，不可删除！");
                    return;
                }
                if (children[index].id !== "") {
                    await this.deleteDimensionAct({id: children[index].id});
                }
                children.splice(index, 1);
                for (let i in children) {
                    children[i].sort = parseInt(i) + 1;
                }
                this.setCurrentQuestionnaire(this.questionnaire);
            },
            multipleDimensionEdit(node, dimension) {
                this.$refs.dimensionEdit.open(dimension);
            },
            renderContent(h, { node, data, store }) {
                    return (
                        <div style="flex: 1; display: flex; align-items: center; justify-content: space-between; font-size: 14px; padding-right: 8px;">
                        <span>
                            <span>{data.sort}</span>
                        </span>
                        <span>
                            <span>{data.name}</span>
                        </span>
                        <span>
                            <span>{data.weight}</span>
                        </span>
                        <span>
                            <span>{data.questionNum}</span>
                        </span>
                        <span>
                        <el-button size='mini' type="text" on-click={ () => this.multipleDimensionEdit(node, data) } >
                            <i class="el-icon-edit" aria-hidden="true"/>
                        </el-button>
                        <el-button size='mini' type="text" on-click={ () => this.remove(node, data) }>
                            <i class="el-icon-delete" aria-hidden="true"/>
                        </el-button>
                        <el-button size='mini' type="text" on-click={ () => this.append(data) }>
                            <i class="el-icon-plus" aria-hidden="true"/>
                        </el-button>
                    </span>
                    </div>);
            },
            isMultipleDim() {
                for (let index in this.questionnaire.dimensions) {
                    if (this.questionnaire.dimensions[index].children.length > 0) {
                        return true;
                    }
                }
            },
            async checkChange() {
                if (!this.isMultipleDimension) {
                    for (const dimension of this.questionnaire.dimensions) {
                        if (dimension.children.length > 0) {
                            this.releaseBinding(dimension.children);
                            for (let child of dimension.children) {
                                if (child.id !== "") {
                                    await this.deleteDimensionAct({id: child.id});
                                }
                            }
                            dimension.children = [];
                        }
                    }
                    this.setCurrentQuestionnaire(this.questionnaire);
                }
            },
            releaseBinding(dimensions) {
                dimensions.forEach(dimension => {
                    dimension.questions.forEach(question => {
                        this.questionnaire.questions.forEach(que => {
                            if (que.sort === question.sort) {
                                que.dimension = '';
                                que.checked = false;
                            }
                        })
                    });
                    if (dimension.children.length > 0) {
                        this.releaseBinding(dimension.children);
                    }
                })
            }
        },
        watch: {
            isMultipleDimension(newValue, oldValue) {
                if (newValue !== oldValue && !this.isMultipleDimension) {
                    for (let j in this.questionnaire.questions) {
                        let isExit = false;
                        for (let i in this.questionnaire.dimensions) {
                            if (this.questionnaire.questions[j].dimension === "") {
                                continue;
                            }
                            if (this.questionnaire.dimensions[i].name === this.questionnaire.questions[j].dimension) {
                                isExit = true;
                                break;
                            }
                        }
                        if (!isExit) {
                            this.questionnaire.questions[j].dimension = "";
                        }
                    }
                    for (let i in this.questionnaire.dimensions) {
                        this.questionnaire.dimensions[i].children = [];
                    }
                    this.setCurrentQuestionnaire(this.questionnaire);
                }
            }
        },
        mounted() {
            this.questionnaire = this.currentQuestionnaire;
            this.isMultipleDimension = this.isMultipleDim();
        }
    }
</script>

<style scoped>
  .el-table-add-row {
    margin-top: 10px;
    width: 100%;
    height: 34px;
    border: 1px dashed #c1c1cd;
    border-radius: 3px;
    cursor: pointer;
    justify-content: center;
    display: flex;
    line-height: 34px;
  }
  .headerItem {
    border: 1px #c1c1cd;
    text-align: center;
  }
  .nameItem {
    border: 1px #c1c1cd;
    text-align: center;
  }
  .numItem {
    border: 1px #c1c1cd;
    text-align: center;
  }
  .operateItem {
    border: 1px #c1c1cd;
    text-align: center;
  }
</style>
